<?php

namespace app\common\library;

/**
 * Token操作类
 */
class ApiToken
{
	
	/**
     * 产生Token
     * @param   string    $type      "md5" 
     */
	public static function token($type = "md5")
	{	
		$type  = is_callable($type) ? $type : 'md5';
        $token = call_user_func($type, $_SERVER['REQUEST_TIME_FLOAT']);
		
        return $token;
	}
	
	public static function is_token($instrument_sn = '')
	{
		if(empty($instrument_sn)) {
			return [];
		}
		
		$data = \app\common\model\ApiToken::get(['instrument_sn' => $instrument_sn]);		
		
		if ($data)
        {
            if (!$data['expiretime'] || $data['expiretime'] > time())
            {
                return $data;
            }
            else
            {	
				$token = $data->getData()['token'];
                self::delete($token);
            }
        }
        return [];	
		
	}

    /**
     * 存储Token
     * @param   string    $token      Token
     * @param   string       $instrument_sn    会员ID
     * @param   int       $expire     过期时长,0表示无限,单位秒
     */
    public static function set($token, $instrument_sn, $expire = 0)
    {
        $expiretime = $expire ? time() + $expire : 0;
        \app\common\model\ApiToken::create(['token' => $token, 'instrument_sn' => $instrument_sn, 'expiretime' => $expiretime]);
        return TRUE;
    }

    /**
     * 获取Token内的信息
     * @param   string  $token 
     * @return  array
     */
    public static function get($token)
    {
        $data = \app\common\model\ApiToken::get($token);
        if ($data)
        {
            if (!$data['expiretime'] || $data['expiretime'] > time())
            {
                return $data;
            }
            else
            {
                self::delete($token);
            }
        }
        return [];
    }

    /**
     * 判断Token是否可用
     * @param   string    $token      Token
     * @param   string       $instrument_sn    会员ID
     * @return  boolean
     */
    public static function check($token, $instrument_sn)
    {
        $data = self::get($token);
        return $data && $data['instrument_sn'] == $instrument_sn ? true : false;
    }

    /**
     * 删除Token
     * @param   string  $token
     * @return  boolean
     */
    public static function delete($token)
    {
        $data = \app\common\model\ApiToken::get($token);
        if ($data)
        {
            $data->delete();
            return true;
        }
        return false;
    }

    /**
     * 删除指定用户的所有Token
     * @param   string     $instrument_sn
     * @return  boolean
     */
    public static function clear($instrument_sn)
    {
        \app\common\model\ApiToken::where('instrument_sn', $instrument_sn)->delete();
        return true;
    }

}
